﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WordDocumentGenerator.Library;
using System.Xml;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Drawing.Charts;
using System.Data;
using DocumentFormat.OpenXml;
using System.Diagnostics;

namespace DbWord
{
    public class MyDocGenerator : DocumentGenerator
    {
        public DateTime RptTime { get; set; }

        /// <summary>
        /// as RecursivePlaceholder every new row reset counter
        /// </summary>
        public int RowIndex { get; set; }

        /// <summary>
        /// chart can't set marker use this index
        /// </summary>
        public int ChartIndex { get; set; }

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="SampleDocumentGenerator"/> class.
        /// </summary>
        /// <param name="generationInfo">The generation info.</param>
        public MyDocGenerator(DocumentGenerationInfo generationInfo)
            : base(generationInfo)
        {
        }

        #endregion

        #region inherit
        public Dictionary<string, PlaceHolderType> MyPlaceCollection { get; set; }

        protected override Dictionary<string, PlaceHolderType> GetPlaceHolderTagToTypeCollection()
        {

            Dictionary<string, PlaceHolderType> dic = new Dictionary<string, PlaceHolderType>();

            XmlDocument doc = new XmlDocument();
            doc.Load(Defs.XmlDocFile);

            XmlNodeList nodelist = doc.SelectNodes(Defs.Xml_PlacePath + "//PlaceHolder");
            foreach (XmlNode node in nodelist)
            {
                PlaceHolderType type = (PlaceHolderType)Enum.Parse(
                    typeof(PlaceHolderType),
                    node.Attributes["Type"].Value);

                switch (type)
                {
                    case PlaceHolderType.Container: break;
                    case PlaceHolderType.Ignore: break;
                    case PlaceHolderType.None: break;
                    case PlaceHolderType.Recursive: 
                        string columnsnode = node.SelectSingleNode("Columns").InnerText;
                        string[] columns = columnsnode.Split(new char[] { ',' }, 
                            StringSplitOptions.RemoveEmptyEntries).Select(o => o.Trim()).ToArray();
                        for (int i = 0; i < columns.Length; i++)
                        {
                            dic.Add(columns[i], PlaceHolderType.NonRecursive);
                        }
                        break;
                    case PlaceHolderType.NonRecursive: break;
                    default: break;
                }
                XmlNode namenode = node.SelectSingleNode("Name");
                if (!string.IsNullOrWhiteSpace(node.InnerText))
                {
                    dic.Add(namenode.InnerText, type);
                }
            }

            MyPlaceCollection = dic;
            return dic;
        }

        protected override void IgnorePlaceholderFound(string placeholderTag, OpenXmlElementDataContext openXmlElementDataContext)
        {
            //throw new NotImplementedException();
        }

        protected override void NonRecursivePlaceholderFound(string placeholderTag, OpenXmlElementDataContext openXmlElementDataContext)
        {
            string tagPlaceHolderValue = string.Empty;
            string tagGuidPart = string.Empty;
            GetTagValue(
                openXmlElementDataContext.Element as SdtElement, 
                out tagPlaceHolderValue, 
                out tagGuidPart);

            Trace.WriteLine(string.Concat("NonRecursive =>", placeholderTag));

            string tagValue = string.Empty;
            string content = string.Empty;

            if (openXmlElementDataContext.DataContext == null)
            {
                if (MyPlaceCollection.ContainsKey(tagPlaceHolderValue))
                {
                    try
                    {
                        content = new Request.Helper().Idb.ExecuteScalar(
                            ParametersCache.Instance.NormalSqlDic[tagPlaceHolderValue].Element("Sql").Value);
                        Trace.WriteLine(string.Concat("Success =>", placeholderTag));

                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(string.Concat("Fail =>", placeholderTag, " => ", ex.Message));
                    }
                }
                if (!string.IsNullOrEmpty(tagValue))
                {
                    this.SetTagValue(
                        openXmlElementDataContext.Element as SdtElement,
                        GetFullTagValue(tagPlaceHolderValue, tagValue));
                }
            }
            else
            {
                DataRow row = openXmlElementDataContext.DataContext as DataRow;

                content = row[RowIndex].ToString();
                RowIndex++;
            }
            
            // Set text without data binding
            this.SetContentOfContentControl(
                openXmlElementDataContext.Element as SdtElement, 
                content);
        }

        protected override void RecursivePlaceholderFound(string placeholderTag, OpenXmlElementDataContext openXmlElementDataContext)
        {
            string tagPlaceHolderValue = string.Empty;
            string tagGuidPart = string.Empty;
            GetTagValue(openXmlElementDataContext.Element as SdtElement, out tagPlaceHolderValue, out tagGuidPart);

            Trace.WriteLine(string.Concat("Recursive =>", placeholderTag));

            // Reuse base class code and handle only tags unavailable in base class
            System.Data.DataTable table = new System.Data.DataTable();
            if (MyPlaceCollection.ContainsKey(tagPlaceHolderValue))
            {
                try
                {
                    table = new Request.Helper().Idb.FillTable(
                        ParametersCache.Instance.NormalSqlDic[tagPlaceHolderValue].Element("Sql").Value);
                    Trace.WriteLine(string.Concat("Success =>", placeholderTag));
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Concat("Fail =>", placeholderTag));
                }
            }

            foreach (System.Data.DataRow row in table.Rows)
            {
                RowIndex = 0;
                SdtElement clonedElement = this.CloneElementAndSetContentInPlaceholders(new OpenXmlElementDataContext()
                {
                    Element = openXmlElementDataContext.Element,
                    DataContext = row
                });
            }
            openXmlElementDataContext.Element.Remove();
        }

        protected override void ContainerPlaceholderFound(string placeholderTag, OpenXmlElementDataContext openXmlElementDataContext)
        {
        }

        #endregion inherit

        //string GetSql(string nodeName)
        //{
        //    XmlDocument doc = new XmlDocument();
        //    doc.Load(Defs.XmlDocFile);

        //    XmlNode node = doc.SelectSingleNode(string.Format(
        //        "{0}/PlaceHolder[Name='{1}']",
        //        Defs.Xml_PlacePath,
        //        nodeName));
        //    string sql = node.SelectSingleNode("Sql").InnerText;
        //    sql = string.Format(sql, RptTime.ToString("yyyyMMdd"));
        //    return sql;
        //}

        
    }
}
